package com.lgr.store.controller;


import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lgr.store.service.MaterialInputService;
import com.lgr.store.utils.AppointStateEnum;
import com.lgr.store.utils.ContextUtils;
import com.lgr.store.utils.ExportToExcel;
import com.lgr.store.utils.LogJournal;
import com.lgr.store.utils.PageObject;
import com.lgr.store.vo.EmpVo;
import com.lgr.store.vo.MaterialInputVo;
import com.lgr.store.vo.MaterialVo;
import com.lgr.store.vo.StorageVo;
import com.lgr.store.vo.SupplierVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/admin/materialInput")
public class MaterialInputController {
    @Resource
    MaterialInputService materialInputService;
    @Resource
    HttpSession session;
  //返回上传结果
    private String errinfo;
    //@Value注解获取application.properties文件中的upload.absPath变量的值
    @Value("${upload.absPath}")
    String absPath;
    @RequestMapping(value="/list")
    public String list(HttpServletRequest request,HttpServletResponse response, MaterialInputVo materialInput, PageObject pager, ModelMap map){
        int cnt = 0;

        //点击菜单，点击分页，点击刷新等操作时批号为null
        if(materialInput.getBatchNo()==null){
            if(request.getSession().getAttribute("materialInput")!=null){
                materialInput=(MaterialInputVo)request.getSession().getAttribute("materialInput");
            }
        }else{
            request.getSession().setAttribute("materialInput", materialInput);
        }
        String sdate1=materialInput.getOprDate();
        String sdate2=materialInput.getOprDate2();

        if(materialInput.getOprDate()!=null && materialInput.getOprDate()!="" && materialInput.getOprDate().length()<=10 && materialInput.getOprDate2()!=null && materialInput.getOprDate2()!=""){
            materialInput.setOprDate(materialInput.getOprDate() +" 00:00:00");
            materialInput.setOprDate2(materialInput.getOprDate2() +" 23:59:59");
        }

        cnt = materialInputService.count(materialInput);
        if(materialInput.getOprFlag()==0){//查询
	        pager.setTotalRows(cnt);
	        List<MaterialInputVo> materialInputList = materialInputService.list(materialInput,pager);
	        materialInput.setOprDate(sdate1);
	        materialInput.setOprDate2(sdate2);
	        map.addAttribute("materialInput",materialInput);
	        pager.setDatas(materialInputList);
	        map.addAttribute("pager",pager);
	        //所有仓库
//	        List<StorageVo> storagelist = materialInputService.listStorage();
	        //所有供应商
	        List<SupplierVo> supplierList = materialInputService.listSupplier();
//	        map.addAttribute("storagelist",storagelist);
	        map.addAttribute("supplierList",supplierList);
	        return "materialInput";	
        }else{//导出
        	int pageSize = pager.getPageRow();
        	pager.setPageRow(cnt);
        	pager.setStartRow(0);
        	List<MaterialInputVo> materialInputList = materialInputService.list(materialInput,pager);
        	materialInput.setOprFlag(0);
        	String path = request.getRealPath("/");
//            String path = System.getProperty("user.dir");

        	try{
//                String path = ResourceUtils.getURL("classpath:").getPath()+"src/main/webapp/";
	        	path = new ExportToExcel().fuLiaoOputput(materialInputList, path, absPath,1);//生成Excel文件
	        	pager.setPageRow(pageSize);
	        	//下载文件
	        	File file = new File(path);   
				String filename = file.getName();   
//				String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();   
				response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes()));   
				response.addHeader("Content-Length", "" + file.length());   
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());   
				response.setContentType("application/octet-stream");   
				InputStream fis = new BufferedInputStream(new FileInputStream(path));   
				byte[] buffer = new byte[1024];
		        int i = -1;
		        while ((i = fis.read(buffer)) != -1) {
		        	toClient.write(buffer, 0, i);
		        }
		        fis.close();
				toClient.write(buffer);   
				toClient.flush();   
				toClient.close();   
        	}catch(Exception e){e.printStackTrace();}
			return null;
        }
    }
    //新增或修改
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request,HttpServletResponse response, ModelMap map, MaterialInputVo materialInput, @RequestParam(value = "orderId")String orderId){
        if(materialInputService.findByOrderId(orderId) != null){
            //修改
            session.setAttribute(AppointStateEnum.LOG.getStateInfo(),LogJournal.setLogParam(2,materialInput));
            materialInputService.update(materialInput);
        }else{
            //新增
            session.setAttribute(AppointStateEnum.LOG.getStateInfo(),LogJournal.setLogParam(1,materialInput));
            materialInputService.add(materialInput);
        }
        PageObject pager = new PageObject();
        pager.setCur_page(1);
        //重新设置查询条件
        materialInput = new MaterialInputVo();
        return list(request,response,materialInput,pager,map);
    }
    //删除
    @RequestMapping(value = "/del")
    public String del(HttpServletRequest request,HttpServletResponse response,Integer []ids,MaterialInputVo materialInput,ModelMap map){
        session.setAttribute(AppointStateEnum.LOG.getStateInfo(),LogJournal.setLogParam(3,materialInput));
        for (Integer id : ids) {
        	materialInputService.delete(id);
		}
        
        PageObject pager = new PageObject();
        pager.setCur_page(1);
        //重新设置查询条件
        materialInput= new MaterialInputVo();
    	if(request.getSession().getAttribute("materialInput")!=null){
    		materialInput=(MaterialInputVo)request.getSession().getAttribute("materialInput");
    	}
        return list(request,response,materialInput,pager,map);
    }
    @RequestMapping(value = "/json")
    @ResponseBody
    public Map json(MaterialInputVo materialInput) throws IOException {
        MaterialInputVo materialInputList = materialInputService.findById(materialInput.getMaterialInputId());
        Map map=new HashMap();
        map.put("materialInputList",materialInputList);
        return map;
    }
    
    @RequestMapping(value = "/updateAduit")
    public String updateAduit(String ids,int status,HttpServletRequest request,HttpServletResponse response,ModelMap map){
    	
    	String [] arr = ids.split(",");
    	for (String id : arr) {
			materialInputService.updateAduit(status, Integer.parseInt(id));
		}
    	
    	MaterialInputVo materialInput = new MaterialInputVo();
    	if(request.getSession().getAttribute("materialInput")!=null){
    		materialInput=(MaterialInputVo)request.getSession().getAttribute("materialInput");
    	}
    	PageObject pager = new PageObject();
    	return list(request,response, materialInput, pager, map);
    }
    //入库
    @RequestMapping(value = "/inStorage")
    public String inStorage(String ids,HttpServletRequest request,HttpServletResponse response,ModelMap map){
    	
    	materialInputService.fuLiaoInStorage(ids);
    	MaterialInputVo materialInput = new MaterialInputVo();
    	if(request.getSession().getAttribute("materialInput")!=null){
    		materialInput=(MaterialInputVo)request.getSession().getAttribute("materialInput");
    	}
    	PageObject pager = new PageObject();
    	return list(request,response, materialInput, pager, map);
    }
    
    @RequestMapping(value = "/miUpload")
    public String miUpload(){
        
        return "miUpload";
    }
    @RequestMapping("/saveExcel")
    //file变量名称必须与miUpload页面中上传文件的控件名称必须一致
    public String saveExcelInfo(@RequestPart("file") MultipartFile file, HttpServletRequest request, ModelMap map) throws IOException {
        String newname = UUID.randomUUID().toString().replace("-", "");
        //获取项目真实路径
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        //获取文件后缀
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        newname += ext;
        //上传后文件相对项目的相对路径
        String relativePath = Paths.get("excels1", newname).toString();
        //上传后文件真实路径
        Path path = Paths.get(rootPath, relativePath);
        //如果保存文件的目录不存在，则创建
        if (!Files.exists(path.getParent())) {
            Files.createDirectory(path.getParent());
        }
        //保存文件
        file.transferTo(path.toFile());
        //解析Excel文件内容
        parsefile(path.toString());

        String path1 = request.getSession().getServletContext().getRealPath("\\");
        File file1=new File(path1+"\\"+relativePath);
        //删除上传的文档
        file1.delete();
        map.addAttribute("errinfo", errinfo);
        return "miUpload";
    }

    public void  parsefile(String filename){
        HSSFWorkbook book = null;
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(filename));
            book = new HSSFWorkbook(fs);
        } catch (Exception e) {
            e.printStackTrace();
        }

        HSSFSheet sheet = book.getSheetAt(0);
        Object[][] data = (Object[][]) null;
        //获取行数
        int r = sheet.getLastRowNum()+1;
        //获取列数
        int c = sheet.getRow(0).getLastCellNum();
        //有3行表头信息不需要读取
        int headRow = 3;
        data = new Object[r - headRow][c];
        for (int i = headRow; i <= r; ++i) {
            HSSFRow row = sheet.getRow(i);//获取第i行数据
            for (int j = 0; j < c; ++j) {
                HSSFCell cell = null;
                try {
                	cell = row.getCell(j);
                	if(j!=2){
                		cell.setCellType(Cell.CELL_TYPE_STRING);
	                    data[i - headRow][j] = cell.getStringCellValue();
                	}else{//第2列是日期类型
	                    data[i - headRow][j] = cell.getDateCellValue();         		
                	}
                } catch (Exception e) {
                    System.out.println("i=" + i + ";j=" + j + ":" + e.getMessage());
                }
            }
        }
        System.out.println("data=" + data);
        //对数据进行合法性验证，并且保存数据到数据表中
        addorUpdate(data);

    }

    public void addorUpdate(Object[][] data){
        int row=data.length;
        int col=0;
        errinfo="";
        String colName="";
        String[] stitle=new String[]{"序号","供应商编码","到货日期","仓库编码","物料编码","物料名称","规格型号","计量单位","采购单号","生产批号","数量"};
        //查询所有的出库数据
        List<StorageVo> storageList = materialInputService.listStorage();
        //从session中获取当前用户信息
        EmpVo empVo = (EmpVo) session.getAttribute(AppointStateEnum.EMPS.getStateInfo());
        for (int i=0;i<row;++i){
            MaterialInputVo mi = new MaterialInputVo();
            col=1;
            //判断供应商编号是否存在
            String supplierCode = data[i][col++]+"";
            SupplierVo supplier = materialInputService.findBysupplierCode(supplierCode);
            if(supplier==null){
            	errinfo = this.errinfo + "第" + (i + 4) + "行的【" + stitle[col - 1] + "】错误、该【" + stitle[col - 1] + "】:不存在<br/>";
                continue;
            }
            mi.setSupplierId(supplier.getSupplierId());
            mi.setSupplierName(supplier.getSupplierName());
            mi.setOprDate(ContextUtils.dateToStrShort((Date)data[i][col++]));
            
            String storageCode = data[i][col++]+"";
            boolean bok=false;
            for (StorageVo s : storageList) {
				if(s.getStorageCode().equals(storageCode)){
					bok=true;
					mi.setStorageId(s.getStorageId());
					mi.setStorageName(s.getStorageName());
					break;
				}
			}
            if(!bok){
            	errinfo = this.errinfo + "第" + (i + 4) + "行的【" + stitle[col - 1] + "】错误、该【" + stitle[col - 1] + "】:不存在<br/>";
                continue;
            }
            String materialCode = data[i][col++]+"";
            MaterialVo mt = materialInputService.findByMaterialCode(materialCode);
            if(mt==null){
            	errinfo = this.errinfo + "第" + (i + 4) + "行的【" + stitle[col - 1] + "】错误、该【" + stitle[col - 1] + "】:不存在<br/>";
                continue;
            }
            mi.setMaterialId(mt.getMaterialId());
            mi.setMaterialCode(mt.getMaterialCode());
            mi.setMaterialName(mt.getMaterialName());
            col++;
            mi.setStyle(data[i][col++]+"");
            mi.setUnitName(data[i][col++]+"");
            mi.setOrderId(data[i][col++]+"");
            mi.setBatchNo(data[i][col++]+"");
            try{
            	mi.setOrderCnt(Float.parseFloat(data[i][col++]+""));
            }catch(Exception e ){
            	errinfo = this.errinfo + "第" + (i + 4) + "行的【" + stitle[col - 1] + "】错误、该【" + stitle[col - 1] + "】:数据格式错误;<br/>";
                continue;
            }
            
            mi.setAduitStatus(1);
            mi.setMaterialInputId(0);
            mi.setOrderNo("");
            mi.setUserName(empVo.getEmpName());
            try{
            	MaterialInputVo mctemp=materialInputService.findByOrderId(mi.getBatchNo());
	            if(mctemp != null){
	            	mi.setMaterialInputId(mctemp.getMaterialInputId());
	                //修改
	                session.setAttribute(AppointStateEnum.LOG.getStateInfo(),LogJournal.setLogParam(2,mi));
	                materialInputService.update(mi);
	            }else{
	                //新增
	                session.setAttribute(AppointStateEnum.LOG.getStateInfo(),LogJournal.setLogParam(1,mi));
	                materialInputService.add(mi);
	            }
	            
            }catch (Exception e){
            	e.printStackTrace();
            	errinfo = this.errinfo + "第" + (i + 4) + "行的数据有误<br/>";
                continue;
            }
        }
        errinfo = this.errinfo +"<br/>导入完成，点击返回查看结果";
    }
}
